package com.springcloud.sc.ucpv5.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springcloud.sc.comm.core.constant.CommonConstants;
import com.springcloud.sc.ucp.v5.api.feign.UcpRemoteDeptService;
import com.springcloud.sc.ucp.v5.api.feign.UcpRemoteUserService;
import com.springcloud.sc.ucp.v5.api.vo.*;
import com.springcloud.sc.ucpv5.client.application.message.DataMessageManager;
import com.springcloud.sc.ucpv5.client.commondata.*;
import com.springcloud.sc.ucpv5.client.commondata.data.*;
import com.springcloud.sc.ucpv5.client.module.datamanager.BaseDataManager;
import com.springcloud.sc.ucpv5.client.module.datamanager.LoginDataManager;

import com.springcloud.sc.ucpv5.service.GroupDetailService;
import com.springcloud.sc.ucpv5.service.JobUcpScheduleService;
import com.springcloud.sc.ucpv5.service.UcpService;
import com.springcloud.sc.ucpv5.tree.*;
import com.springcloud.sc.ucpv5.tree.data.UcpDataUtil;
import com.springcloud.sc.ucpv5.tree.data.WebTreeNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class UcpServiceImpl implements UcpService {

    @Autowired
    private UcpRemoteDeptService ucpRemoteDeptService;

    @Autowired
    private UcpRemoteUserService ucpRemoteUserService;

    @Autowired
    private JobUcpScheduleService jobUcpScheduleService;

    @Autowired
    private RedisTemplate<String , Object> redisTemplate;

    @Autowired
    private GroupDetailService groupDetailService;

    @Autowired
    private UcpDataUtil ucpDataUtil;

    List<InfoTree> trees = Collections.synchronizedList(new ArrayList<>());

    /**
     * 后台管理系统 UCP树节点显示
     * @param id
     * @return
     */
    public WebTreeNode getWebListTree(String id){
        MyNode loginNode = BaseDataManager.getInstance().getLoginNode();
        MyNode node = null;
        //表示系统管理员
        if(id == null || "1".equals(id) ){
            node =  BaseDataManager.getInstance().getLoginNode();
        }else{
            MyUser myUser = BaseDataManager.getInstance().userGet( id );
            if(myUser!=null){
                String loginNodeNumber = myUser.getLogicNodeNumber();
                node = BaseDataManager.getInstance().nodeGet( loginNodeNumber );
            }else{
                node =  BaseDataManager.getInstance().getLoginNode();
            }
        }
        WebTreeNode tempNode = ucpDataUtil.nodeGetNode( node , true);
        return tempNode;
    }

    /**
     * 后台管理系统 UCP树节点显示
     * @param id
     * @return
     */
    public List<WebTreeNode> getWebListTreeOwnGroup(String id){
        MyNode loginNode = BaseDataManager.getInstance().getLoginNode();
        MyNode node = null;
        MyUser myUser = BaseDataManager.getInstance().userGet( id );
        //表示系统管理员
        if(id.equals("1")){
            node =  BaseDataManager.getInstance().getLoginNode();
            List<WebTreeNode> treeNodeList = new ArrayList<WebTreeNode>();
            treeNodeList.add(ucpDataUtil.nodeGetNode( node , true));
            return treeNodeList;
        }else{
            if(myUser!=null){
                String loginNodeNumber = myUser.getLogicNodeNumber();
                node = BaseDataManager.getInstance().nodeGet( loginNodeNumber );
            }else{
                node =  BaseDataManager.getInstance().getLoginNode();
            }
            return ucpDataUtil.nodeGetOwnGroup( node , myUser);
        }
    }

    public WebTreeNode getWebLimitTree(Map<String, Object> params , String userId){
        MyNode loginNode = BaseDataManager.getInstance().getLoginNode();
        MyNode node = null;
        String parentId = params.get("parentId")!=null ? String.valueOf(params.get("parentId")):null;
        //表示系统管理员
        if(userId.equals("1")){
            node =  BaseDataManager.getInstance().getLoginNode();
        }else{
            MyUser myUser = BaseDataManager.getInstance().userGet( userId );
            if(myUser!=null){
                String num = myUser.getIdlData().getGrpList();
                MyGroup tempGroup = BaseDataManager.getInstance().groupGet(num );
                String loginNodeNumber = tempGroup.getLogicNodeNumber();
                node = BaseDataManager.getInstance().nodeGet( loginNodeNumber );
            }else{
                node =  BaseDataManager.getInstance().getLoginNode();
            }
        }
        WebTreeNode tempNode = ucpDataUtil.nodeGetNode( node , true);
        return tempNode;
    }

    public List getNodeTree(Map<String, Object> params , String userId){
        List list = new ArrayList();
        MyNode node = null;
        String parentId = params.get("parentId")!=null ? String.valueOf(params.get("parentId")):null;

        //表示系统管理员
        if(userId.equals("1")){
            if (parentId.equals("-1")){
                node =  BaseDataManager.getInstance().getLoginNode();
                Map map = new HashMap();
                map.put("parent",node.getIdlData().getParentNumber() );
                map.put("text" , node.getIdlData().getNodeNumber() );
                map.put("label" , node.getIdlData().getPhysics_NodeNumber());
                map.put("name",node.getIdlData().getNodeName());
                list.add(map);
            }else{

            }
        }

        return list;
    }


    /**
     *
     * 后台管理系统Page页面显示数据
     * */

    public Page findListById(Map<String, Object> params , String userId){
        return findListById(params , userId, true);
    }
    /**
     *
     * 后台管理系统Page页面显示数据
     * */

    public Page findListById(Map<String, Object> params , String userId, boolean withChild){
        //先清空缓存数据
        ucpDataUtil.clearList();
        Page page = new Page();
        String page1 = String.valueOf( params.get("page") ); //页码
        String limit = String.valueOf( params.get("limit") ); //每页记录数
        String isAsc = String.valueOf( params.get("isAsc") );
        String currentId = String.valueOf( params.get("currentId") );
        String type = String.valueOf( params.get("type") );
        String searchName = String.valueOf( params.get("nodeName") );
        MyNode loginNode = BaseDataManager.getInstance().getLoginNode();
        MyNode node = null;
        List list = new ArrayList();
        //表示系统管理员
        if(userId.equals("1")){
            node =  BaseDataManager.getInstance().getLoginNode();
        }else{
            MyUser myUser = BaseDataManager.getInstance().userGet( userId );
            if(myUser!=null){
                String loginNodeNumber = myUser.getLogicNodeNumber();
                node = BaseDataManager.getInstance().nodeGet( loginNodeNumber );
            }else{
                node =  BaseDataManager.getInstance().getLoginNode();
            }
        }
        if(type.equals("node")){
            MyNode dataNode = BaseDataManager.getInstance().nodeGet( currentId );
            boolean boo =  ucpDataUtil.findPageByNode(dataNode , searchName,withChild );
            if(boo){
                list = ucpDataUtil.getList();
            }
        }else if(type.equals("group")){
            MyGroup dataNode = BaseDataManager.getInstance().groupGet( currentId );
            boolean boo =  ucpDataUtil.findPageByGroup(dataNode , searchName , withChild , true , dataNode );
            if(boo){
                list = ucpDataUtil.getList();
            }
        }else if(type.equals("user")){
            MyUser dataNode = BaseDataManager.getInstance().userGet( currentId );
            Map<String,Object> tempUserMap = new HashMap<String,Object>();
            tempUserMap.put("nodeName",dataNode.getIdlData().getDesc());
            tempUserMap.put("nodeNumber",dataNode.getIdlData().getUserTelno());
            tempUserMap.put("type","User");
            int userType = dataNode.getIdlData().getUserType() ;
            int userTypeData = userType & 0x000000FF;
            int tmp = (userType >> 10) & 0x0000000F;
            userType = userTypeData * 10 + tmp;
            tempUserMap.put("typeChild", userType );

            list.add( tempUserMap );
        }
        int currentPage = Integer.valueOf( page1 ); //当前页码
        int pageSize = Integer.valueOf( limit );  //每页记录数*/
        int totalCount = list.size();

        int pageCount=totalCount/pageSize;
        int fromIndex = pageSize * (currentPage - 1);
        int toIndex = fromIndex + pageSize;
        if (toIndex >= totalCount) {
            toIndex = totalCount;
        }
        if(currentPage>pageCount+1){
            fromIndex=0;
            toIndex=0;
        }
        page.setTotal( totalCount );
        list = list.subList(fromIndex , toIndex );
        page.setRecords( list );
        return page;

    }

    public String saveNode(NodeDO nodeDO){
        String flag = "0";
        NodeCommonRsp nodeCommonRsp = new NodeCommonRsp();
        Node node = new Node();
        MyNode parentNode = BaseDataManager.getInstance().nodeGet( nodeDO.getParentNumber() );
        node.setPhysics_NodeNumber( parentNode.getPhysicsNodeNumber() ); //物理节点
        node.setParentNumber( nodeDO.getParentNumber() ); //父节点号码
        node.setNodeName( nodeDO.getNodeName() ); //节点名称
        node.setIS_VIRTURL(Integer.valueOf(nodeDO.getIsLogic())); //节点类型
        node.setNodeType( Integer.valueOf( nodeDO.getNodeType() )); //通讯隔离标志
        if( nodeDO.getNodeNumber() == null ){
            MyNode myNode = new MyNode(node);
            SecuResult secuResult = DataMessageManager.getInstance().nodeAdd( node.getPhysics_NodeNumber() , node.getParentNumber() , node , nodeCommonRsp , false , false  );
            NodeQueryRsp nodeQueryRsp = new NodeQueryRsp();
            SecuResult result = DataMessageManager.getInstance().nodeQueryNodeList(parentNode.getPhysicsNodeNumber() , parentNode.getLogic_NodeNumber() , nodeQueryRsp , false, false);
            Node[] nodeArry = nodeQueryRsp.NodeList;
            Node n = null;
            for(Node nd :  nodeArry){
                if(nd.getNodeName().equals( nodeDO.getNodeName()  )){
                    n = nd;
                    break;
                }
            }
            if(n!=null){
                ucpRemoteDeptService.saveDeptAPI( node.getNodeName(), n.getNodeNumber(), node.getParentNumber() , "1"  );
            }
            flag = "0";
        }else{
            flag = "1";
        }
        return flag;
    }

    public void updateNode(NodeDO nodeDO){
        MyNode myNode = BaseDataManager.getInstance().nodeGet( nodeDO.getNodeNumber() );
        CommonRsp rsp = new CommonRsp();
        Node node = myNode.getIdlData();
        node.setIS_VIRTURL(Integer.valueOf(nodeDO.getIsLogic())); //节点类型
        node.setNodeType( Integer.valueOf( nodeDO.getNodeType() )); //通讯隔离标志
        node.setNodeName( nodeDO.getNodeName() ); //节点名称
        DataMessageManager.getInstance().nodeModify( node.getPhysics_NodeNumber() , node.getNodeNumber() ,node , rsp , false,false );
        //通过Feign调用接口来更新Web系统中的相关数据、节点对应部门表、组对应角色表、用户对应用户
//        remoteDeptService.updateDeptAPI(myNode.getIdlData().getNodeName() , myNode.getIdlData().getNodeNumber() );
    }


    public void updateGroup(GroupDO groupDO){
        MyGroup myGroup = BaseDataManager.getInstance().groupGet( groupDO.getGroupTelno() );
        CommonRsp rsp = new CommonRsp();
        Group group= myGroup.getIdlData();
        group.setGroupName( groupDO.getGroupName());
        group.setPriority( Integer.valueOf( groupDO.getPriority() ));
        group.setGCallTimer( Integer.valueOf( groupDO.getGCallTimer() ));
        group.setFreeTimer( Integer.valueOf( groupDO.getFreeTimer() ));
        group.setLETime( Integer.valueOf( groupDO.getLETime() ));
        group.setVoiceOpen( Integer.valueOf( groupDO.getVoiceOpen() ));
        group.setGroupType( groupDO.getGroupType() );
        group.setKeep1( groupDO.getKeep1() );
        SecuResult secuResult = DataMessageManager.getInstance().groupMod( myGroup.getPhysicsNodeNumber() , myGroup.getLogicNodeNumber() ,group ,rsp , false , false );

          /*Object json = JSONArray.toJSON(  voipList );

      if(secuResult.getRetCode()>=0){
            boolean b =roleService.updateRoleAPI(group.getGroupName() , group.getGroupTelno() );
            if(b){
                //操作记录
                Object json = JSONArray.toJSON(  voipList );
                jobUcpScheduleService.saveJobUcpSchedule(myGroup.getIdlData().getGroupTelno() , json.toString() );
            }
        }*/
    }

    /**
     * 组内用户分配以及组内用户排序实现
     * @param params
     */
    public boolean DistributionGroup(Map<String, Object> params){
        String groupNumber = (String) params.get("groupNumber");
        List<String> userList = (List<String>) params.get("userNumList");
        boolean bool = true;

        MyGroup myGroup = BaseDataManager.getInstance().groupGet(groupNumber);
        // 先做组内用户排序显示存储
        try{
            try {
                for (int index = 0; index < userList.size(); index++) {
                    try {
                        myGroup.getGroupDataInfo().groupUserLevelSet(userList.get(index), index + "");
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                // 下发组修改操作
                CommonRsp rsp = new CommonRsp();
                SecuResult result = DataMessageManager.getInstance().groupMod(myGroup.getPhysicsNodeNumber(), myGroup.getLogicNodeNumber(), myGroup.getIdlData(), rsp,
                        false, false);
                if (result.getRetCode() != 0) {
                    log.info("UcpServiceImpl DistributionGroup 下发组修改操作 异常  " + groupNumber);
                    bool = false;
                }
            } catch (Exception e) {
                log.info("UcpServiceImpl DistributionGroup 下发组修改操作 异常  " + groupNumber + " " + e.getMessage());
                bool = false;
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        try{
            List<MyUser> myUserList = myGroup.getListModel().getUserList();
            ArrayList<String> addList = new ArrayList<String>();
            ArrayList<String> delList = new ArrayList<String>();

            for(MyUser user : myUserList){
                boolean isDel = true;
                for(String newUser : userList){
                    if(newUser.equals(user.getUserTelNo())){
                        isDel = false;
                        break;
                    }
                }
                // 当前用户在下发的用户列表中没有找到,则做移除用户处理
                if(isDel){
                    delList.add(user.getUserTelNo());
                }
            }
            for(String newUser : userList){
                boolean isAdd = true;
                for(MyUser user : myUserList){
                    if(newUser.equals(user.getUserTelNo())){
                        isAdd = false;
                        break;
                    }
                }
                // 当前下发的用户在当前用户列表没有找到,则做增加用户处理
                if(isAdd){
                    addList.add(newUser);
                }
            }
            // 处理用户组内增加或删除
            SecuResult secuResult = DataMessageManager.getInstance().dealGroupUserOneByOne(myGroup, addList, delList, null);
        }catch(Exception e){
            e.printStackTrace();
            log.info("UcpServiceImpl DistributionGroup 下发组成员分配操作 异常  " + groupNumber + " " + e.getMessage());
            bool = false;
        }

        return bool;
    }

    public boolean updateUserInfo(UserInfoDO userInfoDO ){
        boolean bool = false;
        try {
            // 判断用户是否存在
            MyUser myUser = BaseDataManager.getInstance().userGet( userInfoDO.getUserTelno() );
            if (myUser == null) {
                log.info("修改用户  传入用户数据有误  , 用户不存在 " + userInfoDO.getUserTelno() );
                return  false;
            }
            // 先前用户信息
            UserInfo userInfo = myUser.getUserInfo();
            userInfo.UserName = new String(userInfoDO.getUserName().getBytes("UTF-8"));
            userInfo.Desc = userInfoDO.getDesc();
            userInfo.Priority = Integer.valueOf(userInfoDO.UserPriority);
            String StrIndex = userInfoDO.getUserType();
            int index = Integer.valueOf( StrIndex );
            // wsy 设置父组的号码, 多个父组号码会导致服务器死掉
            userInfo.setGrpList(userInfoDO.getGrpList());
            // 终端类型
            {
                int userType = index / 10;
                int userDevtype = index % 10;
                switch (userDevtype) {
                    case 0:
                        userInfo.UserType = userType;
                        break;
                    case 1:
                        userInfo.UserType = userType | 0x000000400;
                        break;
                    case 2:
                        userInfo.UserType = userType | 0x000000800;
                        break;
                }
            }
            // 根据类型进行赋值
            switch (index) {
                case 31:
                    // 手持终端
                    userInfo.UserIconName = "O_User_15_online.png";
                    break;
                case 30:
                    userInfo.UserIconName = "O_User_13_online.png";
                    break;
                case 32:
                    // 基地台
                    userInfo.UserIconName = "O_User_13_online.png";
                    break;
                case 10:
                    // 调度台
                    userInfo.UserIconName = "O_User_1_online.png";
                    break;
                case 1:
                    // 调度台手柄
                    userInfo.UserIconName = "O_User_11_online.png";
                    break;
                case 0:
                    // 网络联动话机
                    userInfo.UserIconName = "O_User_11_online.png";
                    break;
                case 2:
                    // 摄像头
                    userInfo.UserIconName = "O_Vedio_0_online.png";
                    break;
                default:
                    break;
            }
            CommonRsp rsp = new CommonRsp();
            String physicsNodeNumber = myUser.getPhysicsNodeNumber();
            String logicNodeNumber = myUser.getLogicNodeNumber();
            SecuResult secuResult = DataMessageManager.getInstance().userModify(physicsNodeNumber , logicNodeNumber , userInfo , rsp , false,false );
            bool = true;
            //接口调用
            /*if(secuResult.getRetCode() >=0){
                remoteUserService.updateUserAPI( myUser.getIdlData().getUserTelno() , myUser.getIdlData().getUserName() );
                GroupNodeVoip groupNodeVoip = new GroupNodeVoip();
                List<UserNode> userNodesList =  new ArrayList<UserNode>();
                UserNode userNode = createUserInfoAPI( myUser );
                userNodesList.add( userNode );
                groupNodeVoip.setUserList( userNodesList );
                groupNodeVoip.setOperType(1);
                groupNodeVoip.setName( myUser.getIdlData().getUserName() );
                groupNodeVoip.setNumber( myUser.getIdlData().getUserTelno() );
                Object json = JSONArray.toJSON(  groupNodeVoip );
                jobUcpScheduleService.saveJobUcpSchedule( myUser.getIdlData().getUserTelno() , json.toString() );

            }*/
        } catch (Exception e) {
            log.info("WebService 修改用户 异常  " + userInfoDO + e.getMessage());
            return false;
        }
        return bool;
    }

    public String saveGroup(GroupDO groupDO){
        String groupNum = groupDO.getGroupTelno();
        Group groupInfo = new Group();
        SecuResult result = null;
        try {
            groupInfo.setGroupName( groupDO.getGroupName() );
            groupInfo.setGroupTelno( groupNum );
            // 判断用户是否存在
            MyGroup myGroup = BaseDataManager.getInstance().groupGet(groupNum);
            if (myGroup != null) {
                log.error("组已存在  " + groupNum);
                return null;
            }
            // 默认值
            groupInfo.IconName = "O_Group_0_free.png";
            groupInfo.setGroupType( groupDO.getGroupType() );
            groupInfo.GroupTypeTmp = 0;
            groupInfo.ip = "0.0.0.0";
            groupInfo.port = 0;
            groupInfo.MessageOpen = 0;
            groupInfo.DataSerOpen = 1;
            groupInfo.Priority = 7;
            groupInfo.GroupNodeFlag = 0;
            groupInfo.NodeNumber = "";
            groupInfo.ParGrpTelno = groupDO.getParGrpTelno();
            groupInfo.setVoiceOpen(1);
            groupInfo.setLETime(30);
            groupInfo.setFreeTimer(30);
            groupInfo.setGCallTimer(3600);
            if(groupDO.getKeep1() != null) {
                groupInfo.setKeep1(groupDO.getKeep1());
            }

            if( groupInfo.getGroupType() == 0){
                //固定组
                groupInfo.IconName = "O_Group_0_free.png";
            }
            else if( groupInfo.getGroupType() == 1){
                //临时租
                groupInfo.IconName = "O_Group_2_free.png";
            }
            else if( groupInfo.getGroupType() == 2){
                //应急组
                groupInfo.IconName = "O_Group_2_free.png";
            }

            String physicsNodeNumber = null;
            String logicNodeNumber = null;
            MyGroup parentNode = BaseDataManager.getInstance().groupGet( groupDO.getParGrpTelno() );
            if(parentNode == null) {
                physicsNodeNumber = LoginDataManager.getInstance().getUser().getPhysicsNodeNumber();
                logicNodeNumber = LoginDataManager.getInstance().getUser().getLogicNodeNumber();
            }else {
                physicsNodeNumber = parentNode.getPhysicsNodeNumber();
                logicNodeNumber = parentNode.getLogicNodeNumber();
            }

            try {
                // wsy 20181213 如果不存在异节点号码, 则填写本节点号码
                if(!groupInfo.isOtherNodeGroup()){
                    groupInfo.NodeNumber = logicNodeNumber;
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            CommonRsp rsp = new CommonRsp();
            MyGroup group = new MyGroup( groupInfo , physicsNodeNumber , logicNodeNumber ,0 );
            SecuResult secuResult =  DataMessageManager.getInstance().groupAdd( physicsNodeNumber, logicNodeNumber, groupInfo, rsp, false, false);
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
        return null;
    }

    public void saveJobUcpSchedule(MyGroup myGroup){
        List<GroupNodeVoip> groupNodeVoipList = new ArrayList<GroupNodeVoip>();
        GroupNodeVoip groupNodeVoip = new GroupNodeVoip();
        groupNodeVoip.setNumber( myGroup.getIdlData().getGroupTelno() );
        groupNodeVoip.setName( myGroup.getIdlData().getGroupName() );
        groupNodeVoip.setOperType(1);
        Object json = JSONArray.toJSON(  groupNodeVoip );
        jobUcpScheduleService.saveJobUcpSchedule( myGroup.getIdlData().getGroupTelno() , json.toString() , "pds_group_set" );
    }

    public String saveUserInfo(UserInfoDO userInfoDO ){
        try{
            // 先前用户信息
            UserInfo userInfo = new UserInfo();
//            userInfo.UserTelno = userInfoDO.getUserTelno();
            // 用户类型

            userInfo.setUserTelno( userInfoDO.getUserTelno() );
            userInfo.setUserName( userInfoDO.getUserName() );
            userInfo.setDesc(  userInfoDO.getDesc() );
            userInfo.setPassword( userInfoDO.getPassword() );
            userInfo.setGrpList( userInfoDO.getGrpList() );

            if(userInfo.getUserName() == null ){
                userInfo.setUserName( userInfoDO.getUserTelno() );
            }
            // 默认值
            userInfo.Workplace = "";
            userInfo.Contact = "";
            userInfo.UserMediaType = 65535;
            userInfo.UserMediaID = "0";
            userInfo.zoom = "0";
            userInfo.keep2 = "0";
            userInfo.UserShowType = 1;
            userInfo.Address = "1";
            userInfo.PttPriority = 7;
            userInfo.GroupPriority = 7;
            userInfo.Priority = Integer.valueOf(userInfoDO.UserPriority);
            userInfo.Odb = 0;
            userInfo.longitude = "113.23";
            userInfo.latitude = "23.16";
            userInfo.LocalInfo = new UserLocal();
            String StrIndex = userInfoDO.getUserType();
            int index = Integer.valueOf( StrIndex );

            // 终端类型
            {
                int userType = index / 10;
                int userDevtype = index % 10;
                switch (userDevtype) {
                    case 0:
                        userInfo.UserType = userType;
                        break;
                    case 1:
                        userInfo.UserType = userType | 0x000000400;
                        break;
                    case 2:
                        userInfo.UserType = userType | 0x000000800;
                        break;
                }
            }
            // 根据类型进行赋值
            switch (index) {
                case 31:
                    // 手持终端
                    userInfo.UserIconName = "O_User_15_online.png";
                    break;
                case 30:
                    userInfo.UserIconName = "O_User_13_online.png";
                    break;
                case 32:
                    // 基地台
                    userInfo.UserIconName = "O_User_13_online.png";
                    break;
                case 10:
                    // 调度台
                    userInfo.UserIconName = "O_User_1_online.png";
                    break;
                case 0:
                    // 网络联动话机
                    userInfo.UserIconName = "O_User_11_online.png";
                    break;
                case 1:
                    // 外线手机
                    userInfo.UserIconName = "O_Vedio_53_online.png";
                    break;
                case 2:
                    // 外线固话
                    userInfo.UserIconName = "O_Vedio_54_online.png";
                    break;
                case 60:
                    // 摄像头
                    userInfo.UserIconName = "O_User_60_online.png";
                    break;
                case 50:
                    // 智能终端
                    userInfo.UserIconName = "O_User_16_online.png";
                    break;
                case 80:
                    // 智能终端
                    userInfo.UserIconName = "O_User_16_online.png";
                    break;
                case 110:
                    // 4G执法记录仪
                    userInfo.UserIconName = "O_User_63_online.png";
                default:
                    userInfo.UserIconName = "O_User_16_online.png";
                    break;
            }
            // 补充业务的来电显示和会议功能
            List<SSInfoType> infoTypes = new ArrayList<SSInfoType>();
            SSInfoType infoType = new SSInfoType();
            infoType.type = 234;
            infoType.open = 1;
            infoType.SSInfoParaList = new SSInfoPara[] {};
            infoTypes.add(infoType);
            infoType = new SSInfoType();
            infoType.type = 17;
            infoType.open = 1;
            infoType.SSInfoParaList = new SSInfoPara[] {};
            infoTypes.add(infoType);
            userInfo.SSInfoTypelist = new SSInfoType[infoTypes.size()];
            for (int k = 0; k < infoTypes.size(); k++) {
                userInfo.SSInfoTypelist[k] = infoTypes.get(k);
            }
            MyGroup myGroup = BaseDataManager.getInstance().groupGet( userInfoDO.getGrpList() );
            String physicsNodeNumber = myGroup.getPhysicsNodeNumber();
            String logicNodeNumber = myGroup.getLogicNodeNumber();
            CommonRsp rsp = new CommonRsp();
            MyUser tempMyUser = new MyUser(userInfo , physicsNodeNumber , logicNodeNumber , 0);
            SecuResult secuResult = DataMessageManager.getInstance().userAdd(physicsNodeNumber , logicNodeNumber , userInfo  , rsp ,false,false );
            if(secuResult.getRetCode() >=0){
                //只保存调度台用户数据
                if(index == 10){
                    //保存用户信息至WEB系统
                    UserVO userVO = new UserVO();
                    userVO.setUserId( userInfo.getUserTelno() );
                    userVO.setUsername( userInfo.getUserTelno() );
                    userVO.setPassword( userInfo.getPassword() );
                    userVO.setDeptId( logicNodeNumber );
                    userVO.setRoleId( userInfo.getGrpList() );
                    userVO.setSystemId( CommonConstants.STATUS_NORMAL );
                    boolean bool =  ucpRemoteUserService.saveUserAPI(  userVO );
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }


    public NodeDO getNode(Map<String, Object> params) {
        String nodeId = String.valueOf(params.get("id"));
        MyNode myNode = BaseDataManager.getInstance().nodeGet( nodeId );
        NodeDO nodeDO = new NodeDO();
        Node node = myNode.getIdlData();
        //1表示虚拟节点，没有节点号码跟密码
        if(node.IS_VIRTURL == 1){
            nodeDO.setIsLogic( String.valueOf(node.getIS_VIRTURL()) ); //节点类型
            nodeDO.setNodeType( String.valueOf(node.getNodeType()) );  //通讯隔离标志
            nodeDO.setParentNumber( node.getParentNumber() );  //父节点号码
            MyNode tempMyNode = BaseDataManager.getInstance().nodeGet(  node.getParentNumber() );
            nodeDO.setParentName( tempMyNode.getIdlData().getNodeName() );
            nodeDO.setPhysics_NodeNumber( node.getPhysics_NodeNumber() ); //物理节点号码
            nodeDO.setNodeName( node.getNodeName() );  //节点名称
            nodeDO.setNodeNumber( node.getNodeNumber() );
        }else{


        }
        return nodeDO;

    }

    public GroupDO getGroup(Map<String, Object> params) {
        String groupId = String.valueOf(params.get("id"));
        MyGroup myGroup = BaseDataManager.getInstance().groupGet(groupId);
        GroupDO groupDo = new GroupDO();
        String parentId = myGroup.getIdlData().getParGrpTelno();
        groupDo.setFreeTimer( String.valueOf(myGroup.getIdlData().getFreeTimer()));
        groupDo.setParGrpTelno(  parentId );
        MyGroup tempGroup = BaseDataManager.getInstance().groupGet(parentId);
        MyNode tempNode = BaseDataManager.getInstance().nodeGet( parentId );
        if(tempGroup!=null){
            groupDo.setParentName( tempGroup.getIdlData().getGroupName() );
        }
        if(tempNode!=null){
            groupDo.setParentName(tempNode.getIdlData().getNodeName());
        }
        groupDo.setGroupTelno( myGroup.getIdlData().getGroupTelno() );
        groupDo.setGroupName( myGroup.getIdlData().getGroupName() );
        groupDo.setParGrpTelno( myGroup.getIdlData().getParGrpTelno() );
        groupDo.setGCallTimer( String.valueOf( myGroup.getIdlData().getGCallTimer() ) );
        groupDo.setFreeTimer( String.valueOf( myGroup.getIdlData().getFreeTimer() ));
        groupDo.setLETime( String.valueOf( myGroup.getIdlData().getLETime() ));
        groupDo.setVoiceOpen( String.valueOf( myGroup.getIdlData().getVoiceOpen() ));
        groupDo.setNodeNumber( myGroup.getIdlData().getNodeNumber()  );
        groupDo.setPriority( String.valueOf(myGroup.getIdlData().getPriority()) );
        groupDo.setGroupType( myGroup.getIdlData().getGroupType() );
        groupDo.setKeep1( myGroup.getIdlData().getKeep1() );
        return groupDo;
    }

    public UserInfoDO getUser(Map<String, Object> params) {

        UserInfoDO userInfoDO = new UserInfoDO();
        String userInfoId = String.valueOf(params.get("id"));
        MyUser myUser = BaseDataManager.getInstance().userGet(userInfoId);
        String parentId = myUser.getIdlData().getGrpList();
        String tempParentId = null;
        if(parentId!=null){
            int indexXY = parentId.indexOf("#");
            if(indexXY>0){
                tempParentId =   parentId.split("#")[0];
            }else{
                tempParentId = parentId;
            }
        }
        MyGroup myGroup = null;
        if(tempParentId!=null){
            myGroup = BaseDataManager.getInstance().groupGet( tempParentId );
        }
        userInfoDO.setGrpList( tempParentId );
        if (myGroup!=null){
            userInfoDO.setParentName( myGroup.getIdlData().getGroupName() );
        }
        userInfoDO.setNodeNumber( myGroup.getIdlData().getNodeNumber() );
        int userType = myUser.getIdlData().getUserType() ;
        //此处做数据与前端数据对应
        int userTypeData = userType & 0x000000FF;
        int tmp = (userType >> 10) & 0x0000000F;
        userType = userTypeData * 10 + tmp;
        userInfoDO.setUserType( String.valueOf(  userType ) );
        userInfoDO.setUserTelno( myUser.getIdlData().getUserTelno() );
        userInfoDO.setDesc( myUser.getIdlData().getDesc() );
        userInfoDO.setUserPriority( String.valueOf(myUser.getIdlData().getPriority()) );
        userInfoDO.setUserName( myUser.getIdlData().getUserName() );
        return userInfoDO;
    }

    public void deleteNode(String nodeId){
        MyNode myNode = BaseDataManager.getInstance().nodeGet( nodeId);
        Node node = myNode.getIdlData();
        CommonRsp rsp = new CommonRsp();
        DataMessageManager.getInstance().nodeDel(myNode.getPhysicsNodeNumber(),myNode.getLogic_NodeNumber(),node , rsp , false,false );
//        remoteDeptService.deleteDeptAPI( nodeId );
    }

    public boolean deleteGroup(String groupId){
        try{
            MyGroup myGroup = BaseDataManager.getInstance().groupGet( groupId );
            Object json = null;
        /*if(myGroup!=null){
            List<GroupNodeVoip> groupNodeVoipsList= new ArrayList<>();
            GroupNodeVoip groupNodeVoip = new GroupNodeVoip();
            groupNodeVoip.setNumber( myGroup.getIdlData().getGroupTelno() );
            groupNodeVoip.setName( myGroup.getIdlData().getGroupName());
            groupNodeVoip.setOperType(2);
            List<UserNode> userNodesList =  updateUserByGroupAPI(myGroup);
            groupNodeVoip.setUserList( userNodesList );
            groupNodeVoipsList.add( groupNodeVoip );
            json = JSONArray.toJSON(  groupNodeVoipsList );
        }*/
            Group group = myGroup.getIdlData();
            CommonRsp rsp = new CommonRsp();
            SecuResult secuResult = DataMessageManager.getInstance().groupDel(myGroup.getPhysicsNodeNumber() , myGroup.getLogicNodeNumber() ,group ,rsp , false, false );
            if (secuResult.getRetCode() ==0){
                return true;
            }else{
                return false;
            }
        /*if(secuResult.getRetCode()>=0){
            boolean bool = roleService.deleteRoleAPI(groupId);
            if(bool){
                jobUcpScheduleService.saveJobUcpSchedule(myGroup.getIdlData().getGroupTelno() , json.toString() );
            }
        }*/
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteUserInfo(String userId ){
        MyUser myUser = BaseDataManager.getInstance().userGet( userId );
        User user = myUser.getIdlData();
        CommonRsp rsp = new CommonRsp();
        DataMessageManager.getInstance().userDel(myUser.getPhysicsNodeNumber() , myUser.getLogicNodeNumber() ,user ,rsp , false , false  );
        return ucpRemoteUserService.deleteUserAPI( userId );
    }

    public boolean delete(Map<String, Object> params , String userId){
        String id = String.valueOf(params.get("id"));
        String type  = String.valueOf(params.get("type"));
        boolean bool  = false;
        if(type.equals("Node")){
            this.deleteNode( id );
            bool = true;
        }else if(type.equals("Group")){
            bool = this.deleteGroup(id);
        }else if(type.equals("User")){
            if(String.valueOf(userId).equals( id )){
                return false;
            }else{
                bool = this.deleteUserInfo(id);
            }
        }
        return bool;
    }

    @Override
    public List getUserByGroupNumber(String groupNumber) {
        List<Map> userList = new ArrayList<>();
        MyGroup myGroup = BaseDataManager.getInstance().groupGet( groupNumber );
        if (myGroup!=null){
            ArrayList<MyUser> myUserList = myGroup.getListModel().getUserList();
            if(myUserList!=null && !myUserList.isEmpty()){
                myUserList.forEach(user ->{
                    UserNode userNode = new UserNode();
                    Map map = new HashMap();
                    map.put("nodeName", user.getIdlData().getDesc());
                    map.put("nodeNumber", user.getIdlData().getUserTelno());
                    userList.add( map );
                });
            }
        }
        return userList;
    }

    @Override
    public List getUserListByUserNumber(String userNumber) {
        MyUser myUser = BaseDataManager.getInstance().userGetByTelNum( userNumber );
        String[] arryGrp = new String[]{};
        if (myUser!=null){
            String grpList = myUser.getIdlData().getGrpList();
            if (grpList!=null){
                arryGrp = grpList.split("#");
            }
        }
        List  list = new ArrayList();
        for (int i = 0 ; i<arryGrp.length ; i++){
            List tempList = this.getUserListByGroupNumber(arryGrp[i]);
            list.addAll( tempList );
        }
        HashSet h = new HashSet( list );
        list.clear();
        list.addAll(h);
        return list;
    }

    public List getUserListByGroupNumber(String groupNumber){
        List userList = new ArrayList<>();
        MyGroup myGroup = BaseDataManager.getInstance().groupGet( groupNumber );
        if (myGroup!=null){
            ArrayList<MyUser> myUserList = myGroup.getListModel().getUserList();
            if(myUserList!=null && !myUserList.isEmpty()){
                myUserList.forEach(user ->{
                    UserDO userNode = new UserDO();
                    userNode.setAddtime( user.getIdlData().getAddtime() );
                    userNode.setDesc( user.getIdlData().getDesc() );
                    userNode.setGrpList(user.getIdlData().getGrpList() );
                    userNode.setLatitude( user.getIdlData().getLatitude() );
                    userNode.setLongitude( user.getIdlData().getLongitude() );
                    userNode.setPassword( user.getIdlData().getPassword() );
                    userNode.setPriority( user.getIdlData().getPriority() );
                    userNode.setUserIconName( user.getIdlData().getUserIconName() );
                    userNode.setUserMediaID( user.getIdlData().getUserMediaID() );
                    userNode.setUserName( user.getIdlData().getUserName() );
                    userNode.setUserShowType( user.getIdlData().getUserShowType() );
                    userNode.setUserStatus( user.getIdlData().getUserStatus() );
                    userNode.setUserTelno( user.getIdlData().getUserTelno() );
                    userNode.setUserType( user.getIdlData().getUserType() );
                    userNode.setZoom( user.getIdlData().getZoom() );
//                    BeanUtils.copyProperties(user, userNode);
                    userList.add( userNode );
                });
            }
        }
        return userList;
    }

    public List<GroupNode> getGingleGroupInfo(String groupNumber){
        List<GroupNode> list = new ArrayList<>();
        MyGroup myGroup = BaseDataManager.getInstance().groupGet( groupNumber );
        GroupNode groupNode = new GroupNode();
        if(myGroup!=null){
            groupNode.setName( myGroup.getIdlData().getGroupName() );
            groupNode.setNumber( myGroup.getIdlData().getGroupTelno() );
            groupNode.setSign( myGroup.getIdlData().getKeep1() );
            List<MyUser> myUserList = myGroup.getListModel().getUserList();
            if(myUserList!=null && !myUserList.isEmpty()){
                List<UserNode> userList = new ArrayList<>();
                myUserList.forEach(user ->{

                    UserNode userNode = new UserNode();
                    int userType = user.getIdlData().getUserType();
                    int userTypeData = userType & 0x000000FF;
                    int tmp = (userType >> 10) & 0x0000000F;
                    userType = userTypeData * 10 + tmp;
                    if(userType == 1 || userType == 2 ){
                        userNode.setUserType( "1" );
                    }else{
                        userNode.setUserType( "0" );
                    }
                    userNode.setName( user.getIdlData().getUserName() );
                    userNode.setNumber( user.getIdlData().getUserTelno() );
                    userNode.setPassword( user.getIdlData().getPassword() );

                    //outcid 属性
                    try{
                        if(!user.getUserInfoData().getOtherInfo().outcid.equals("")){
                            userNode.setOutcid(user.getUserInfoData().getOtherInfo().outcid);
                        }
                    }catch (Exception e){
                        //e.printStackTrace();
                    }

                        try {
                            // 从缓存额外信息的iconname字段中解析出来该用户可发起语音发布权限的组列表
                            MyUserInfoOtherData otherInfo = JSON.parseObject(user.getUserInfo().getUserIconName(), MyUserInfoOtherData.class);
                            if(otherInfo.voiceAuthorityGroupList != null && otherInfo.voiceAuthorityGroupList.size() > 0){
                                // 如果组列表不为空, 则具有语音发布权限
                                userNode.setVoiceAuthority("1");
                                List<VoiceAuthorityNode> voiceAuthorityNodeList = new ArrayList<>();
                                for(String groupNumber_ : otherInfo.voiceAuthorityGroupList){
                                    try{
                                        MyGroup group_tmp = BaseDataManager.getInstance().groupGet(groupNumber_);
                                        if(group_tmp == null){
                                            System.out.println("JobUcpScheduleServiceImpl 用户修改通知, 组不存在:" + groupNumber_);
                                        }
                                        else if(!group_tmp.isYingJiZu()){
                                            System.out.println("JobUcpScheduleServiceImpl 用户修改通知, 组不是应急组:" + groupNumber_);
                                        }
                                        else if(group_tmp.isYingJiZu()){
                                            VoiceAuthorityNode voiceAuthorityNode = new VoiceAuthorityNode();
                                            voiceAuthorityNode.setNumber(groupNumber_);
                                            voiceAuthorityNodeList.add( voiceAuthorityNode );
                                        }
                                    }catch(Exception e){
                                        e.printStackTrace();
                                    }
                                }
                                userNode.setVoiceAuthorityGroupList( voiceAuthorityNodeList );
                            }
                            else{
                                // 可发布的组为空, 则不具有发布权限
                                userNode.setVoiceAuthority("0");
                            }
                        } catch (Exception e) {
                            // TODO: handle exception
                        }

                    userList.add( userNode );

                });
                groupNode.setUserList( userList );
            }
            list.add( groupNode );
        }
        return list;
    }

    /**
     * 对外提供的查询接口接口
     * @param groupNumber
     * @return
     */
    public String getUserInfoListTreeByGroupNumber(String groupNumber){
        List<GroupNode> list = new ArrayList<>();
        String jsonStr = null;
        if( groupNumber.equals("-1") || groupNumber.toUpperCase().equals("ALL") ){
            //表示拿所有数据
//            list = getAllUserInfoListTreeByGroup();
            //直接去缓存中拿
//            list = BaseDataManager.getInstance().getGroupNodeList();
            jsonStr = redisTemplate.opsForValue().get( "userTreeList").toString();
        }else{
            list = getGingleGroupInfo( groupNumber );
            jsonStr =  JSONObject.toJSONString( list );
        }
        return jsonStr;
    }

    public void startBranchs(Boolean bool , MyGroup childMyGroup){
        getGroupNodeByGroupFirst(childMyGroup);

    }


    public static boolean needrefresh = false;
    public static boolean isrefresh = false;

    public void getAllUserInfoListTreeByGroup(){
        if(!needrefresh && !isrefresh){
            ;
        }
        else if(isrefresh){
            needrefresh = true;
            return;
        }
        isrefresh = true;
        needrefresh = false;
        MyNode myNode = BaseDataManager.getInstance().getCurrentNode();
        //获取所有的组,即开始遍历所有的组信息，然后根据组信息来获取所有
        if(myNode!=null){
            List<MyNode>  myNodes =  myNode.getListModel().getNodeList();
            if(myNodes!=null && !myNodes.isEmpty()){
                myNodes.forEach(childMyNode->{
                    List<MyGroup>  childMyGroupList = childMyNode.getListModel().getGroupList();
                    if(childMyGroupList!=null && !childMyGroupList.isEmpty()){
                        childMyGroupList.forEach(childMyGroup->{
                            getGroupNodeByGroupFirst(childMyGroup);
                        });
                    }
                });
            }
            List<MyGroup>  childMyGroupList = myNode.getListModel().getGroupList();
            if(childMyGroupList!=null && !childMyGroupList.isEmpty()){
                childMyGroupList.forEach(childMyGroup->{
                    getGroupNodeByGroupFirst(childMyGroup);
                });
            }
        }
        try{
            Thread.sleep(6000);
            String jsonStr =  JSONObject.toJSONString( userTreeList );
            redisTemplate.opsForValue().set("userTreeList" , jsonStr);
        }catch (InterruptedException iex){
            iex.printStackTrace();
        }finally {
            userTreeList.clear();
        }
        isrefresh = false;

        if(needrefresh){
            getAllUserInfoListTreeByGroup();
        }

    }

    private ExecutorService executor = Executors.newCachedThreadPool();
    public void getGroupNodeByGroupFirst(MyGroup childMyGroup){
        executor.submit(new Runnable(){
            public void run(){
                try{
                    GroupNode groupNode = groupDetailService.getGroupNodeByGroup(childMyGroup);
                    Thread.sleep(90);
                    if( groupNode !=null && (groupNode.getUserList()!=null && !groupNode.getUserList().isEmpty())){
                        userTreeList.add( groupNode );
                    }
                }catch (Throwable ex){
                    ex.printStackTrace();
                }finally {

                }
            }
        });
    }
    //************************************************************

    private List<GroupNode> userTreeList = Collections.synchronizedList(new ArrayList<>() );

    public void setClear(){
        userTreeList.clear();
    }



}
